package com.example.win.android_banduyujia.peopleactivity.activity.activity.openactivity;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.example.win.android_banduyujia.R;
import com.example.win.android_banduyujia.http.request.UpdaloadRequest;
import com.example.win.android_banduyujia.http.response.BaseHttpResponse;
import com.example.win.android_banduyujia.lib.util.FileUtils;
import com.example.win.android_banduyujia.lib.util.StrUtils;
import com.example.win.android_banduyujia.login.application.LoginApplication;
import com.example.win.android_banduyujia.peopleactivity.ui.activity.BaseTitleBarActivity;
import com.example.win.android_banduyujia.peopleactivity.ui.bitmap.Bimp;

import java.io.File;

/**
 * Created by Win on 2015/9/10.
 */
public class AsanapicActivity  extends BaseTitleBarActivity {

    private String  mUpload=" ";
    private GridView    noScrollgridview;
    public  GridAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_upload_page);

        InitTitles();
        InitViews();
    }

    private void InitTitles() {
        showLeftBackButton();
        setTitle(R.string.text_view_assnap_picture);
        setRightTextViewListener(R.string.text_view_assnap_upload, mRightListener);
    }

    private View.OnClickListener mRightListener = new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            if(StrUtils.isEmpty(mUpload)){
                showToast(R.string.text_view_assnap_picture);
                return;
            }
            Updaload();
        }
    };

    private void Updaload() {
        UpdaloadRequest request = new UpdaloadRequest(LoginApplication.getInstance().getAccessToken());
        request.doRequestFile(AsanapicActivity.this, BaseHttpResponse.class, mUpdaloadHandler, true, mUpdaloadHandler, path);
    }

    private Handler mUpdaloadHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            showToast("上传成功");
            Log.v("avatar", "yes");
            finish();
        }
    };

    private void InitViews() {
        noScrollgridview= (GridView) findViewById(R.id.noScrollgridview);
        noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        adapter = new GridAdapter(this);
        adapter.update1();
        noScrollgridview.setAdapter(adapter);
        noScrollgridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == Bimp.bmp.size()) {
                    new PopupWindows(AsanapicActivity.this, noScrollgridview);
                } else {
                    Intent intent = new Intent(AsanapicActivity.this, AssPictureActivity.class);
                    intent.putExtra("ID", position);
                    startActivity(intent);
                }
            }
        });
    }

    public class GridAdapter extends BaseAdapter {

        private LayoutInflater inflater; // 试图容器
        private int selectedPosition = -1; // 选中的位置
        public boolean  shape;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        public void setSelectedPosition(int position) {
            this.selectedPosition = position;
        }

        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return (Bimp.bmp.size() +1);
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder  holder = null;
            // System.out.println("测试列表=" + position);
            if(convertView == null){
                convertView = inflater.inflate(R.layout.view_picture_grid_item, parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView.findViewById(R.id.view_item_grid_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.image.setVisibility(View.VISIBLE);

            if (position == Bimp.bmp.size()) {
                holder.image.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_addpic_unfocused));
            } else {
                holder.image.setImageBitmap(Bimp.bmp.get(position));
            }if (position == 9) {
                holder.image.setVisibility(View.GONE);
            }
             return convertView;
        }

        public void update1() {
            loading1();
        }

        public class ViewHolder{
            ImageView  image;
        }

        Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 1:
                        adapter.notifyDataSetChanged();
                        break;
                }
                super.handleMessage(msg);
            }
        };



        private void loading1() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true){
                        if(Bimp.max == Bimp.drr.size()){
                            Message  message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                            break;
                        }else{
                            try{
                                String path = Bimp.drr.get(Bimp.max);
                                System.out.println(path);
                                Bitmap bm = Bimp.revitionImageSize(path);
                                Bimp.bmp.add(bm);
                                String newStr = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
                                FileUtils.saveBitmap(bm, "" + newStr);
                                Bimp.max += 1;
                                Message message = new Message();
                                message.what = 1;
                                handler.sendMessage(message);
                            } catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }).start();
        }
    }

    @Override
    protected void onRestart() {
        adapter.update1();
        super.onRestart();
    }

    public class PopupWindows extends PopupWindow{

        public PopupWindows(Context mContext, View parent) {
             View view = View.inflate(mContext, R.layout.title_pic_item, null);

            view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins));
            LinearLayout ll_popup= (LinearLayout) view.findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.push_bottom_in_2));

            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();

            Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
            Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
            Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);
            bt1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    photo();
                    dismiss();
                }
            });
            bt2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(AsanapicActivity.this, TestPicActivity.class));
                    dismiss();
                }
            });
            bt3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
    }

    private static final int TAKE_PICTURE = 0x000000;
    private static final int REQUEST_CODE_ALBUM = 0X006;
    private String path = "";
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
    }

    private void photo() {
        String  status= Environment.getExternalStorageState();
        if(status.equals(Environment.MEDIA_MOUNTED)){
            File dir = new File(Environment.getExternalStorageDirectory() + "/myimage/");
            if(!dir.exists())
                dir.mkdirs();

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File  file = new File(dir, String.valueOf(System.currentTimeMillis() + ".jpg"));
            path = file.getPath();
            Uri imageUri = Uri.fromFile(file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
            startActivityForResult(intent, TAKE_PICTURE);
        }else{
            Toast.makeText(AsanapicActivity.this, "没有存储卡", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case TAKE_PICTURE:
                 if(Bimp.drr.size() < 9 && resultCode == -1){
                     Bimp.drr.add(path);
                 }
                break;
            case REQUEST_CODE_ALBUM:
                saveImage(requestCode);
                break;
        }
    }

    private void saveImage(int requestCode) {

    }
}
